import os

from flask import Flask, render_template, url_for, request, send_from_directory, flash, redirect
from flask_ckeditor import CKEditor, upload_fail, upload_success
from ckeditor_form import RichTextForm
from flask_wtf import CSRFProtect

# 根目录
basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.secret_key = 'hello xiao'
app.config['CKEDITOR_PKG_TYPE'] = 'standard'  # basic, standard, full
app.config['CKEDITOR_SERVE_LOCAL'] = True
app.config['CKEDITOR_FILE_UPLOADER'] = 'upload'
app.config['CKEDITOR_ENABLE_CSRF'] = True  # 不使用CSRF保护，可以注释本句
app.config['UPLOADED_PATH'] = os.path.join(basedir, 'uploads/ckeditor')

ckeditor = CKEditor(app)
csrf = CSRFProtect(app)  # 不使用CSRF保护，可以注释本句


@app.route('/editor', methods=['get', 'post'])
def ckeditor_index():
    form = RichTextForm()
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        result = {'title': title, 'body': body}

        if form.save.data:  # 如果保存按钮被单击
            flash('Data is saved!')
        elif form.submit.data:  # 如果发布按钮被单击
            flash('Data is published!')

        return render_template('ckeditor/post.html', result=result)
    return render_template('ckeditor/ckeditor.html', form=form)


@app.route('/files/<filename>')
def uploaded_files(filename):
    path = app.config['UPLOADED_PATH']
    return send_from_directory(path, filename)


@app.route('/upload', methods=['post'])
def upload():
    f = request.files.get('upload')
    extension = f.filename.split('.')[1].lower()
    if extension not in ['jpg', 'gif', 'png', 'jpeg']:
        return upload_fail(message='Image Only!')
    f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename))
    url = url_for('uploaded_files', filename=f.filename)
    return upload_success(url=url)
